/**
 *
 */
Ext.define('vacake.controller.Product', {
    extend: 'Ext.app.Controller',
    productInfo: '',
    config: {
        routes: {
            'loadProduct/:id': 'loadProduct'
        },
        refs: {
            mainView: 'mainView',
            categoryView: 'categoryView',
            shoppingBalanceView: 'shoppingBalanceView',
            product: 'product',
            backButton: 'product button[action=back_button]',
            numberSpinner: 'product #numbers',
            radioFields: 'product radiofield[name=standard]',
            addCarsButton: 'product #addCars',
            sellProductButton: 'product #sellProduct',
            productCollectButton: 'product #productCollect'
        },
        control: {
            backButton: {
                tap: function () {
                     var backid = Ext.Viewport.getInnerItems().length - 2;
                     Ext.Viewport.remove(this.getProduct(), true);
                     Ext.Viewport.setActiveItem(backid);
                }
            },
            numberSpinner: {
                spindown: function (spinner, value) {
                    var radioValue = this.getRadioFields().getGroupValue();
                    Ext.each(productInfo.standards, function (standard) {
                        var standPrice;
                        if (standard.cpsid == radioValue) {
                            if (productInfo.isviewbate) {
                                standPrice = standard.reprice
                            } else {
                                standPrice = standard.price
                            }
                            Ext.getCmp('countPrice').setValue('￥' + (standPrice * value));
                            return false;
                        }
                    });
                },
                spinup: function (spinner, value) {
                    var radioValue = this.getRadioFields().getGroupValue();
                    Ext.each(productInfo.standards, function (standard) {
                        var standPrice;
                        if (standard.cpsid == radioValue) {
                            if (productInfo.isviewbate) {
                                standPrice = standard.reprice
                            } else {
                                standPrice = standard.price
                            }
                            Ext.getCmp('countPrice').setValue('￥' + (standPrice * value));
                            return false;
                        }
                    });
                }
            },
            radioFields: {
                check: function (radiofield) {
                    Ext.each(productInfo.standards, function (standard) {
                        var standPrice;
                        if (standard.cpsid == radiofield.getValue()) {
                            if (productInfo.isviewbate == 1) {
                                standPrice = standard.reprice
                                Ext.getCmp('viewProductPrice').setHidden(false);
                            } else {
                                standPrice = standard.price
                                Ext.getCmp('viewProductPrice').setHidden(true);
                            }
                            Ext.getCmp('showProductPrice').setHtml('<S>￥'+standard.price+' </S>');
                            Ext.getCmp('countPrice').setValue('￥' + (standPrice * Ext.getCmp('numbers').getValue()));
                            return false;
                        }
                    });
                }
            },
            addCarsButton: {
                tap: 'addCars'
            },
            sellProductButton: {
                tap: 'sellProduct'
            },
            productCollectButton: {
                tap: 'collectProduct'
            }
        }
    },
    loadProduct: function (cpid) {
        var product = this.getProduct();
        if (product == null) {
            product = Ext.create('vacake.view.Product');
        }
        //增加产品的浏览量
        Ext.Ajax.request({
            url: Global.api_url + '/cloud/1/product_viewnum_update',
            params: {cpid: cpid},
            scope: this});
        Ext.Ajax.request({
            url: Global.api_url + '/cloud/1/product_info_get',
            params: {cpid: cpid},
            scope: this,
            success: function (response) {
                var result = Ext.decode(response.responseText);
                if (result.Variables.Result.code == 0) {
                    productInfo = result.Variables.data;
                    if (Ext.isEmpty(productInfo)) {
                        cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", ['请求失败,暂时无法取得此产品的信息！']);
                      //  Ext.Msg.alert('请求失败', '暂时无法取得此产品的信息！');
                        return false;
                    } else {
                        var myAdPicItems = [];
                        if (!Ext.isEmpty(productInfo.photos)) {
                            Ext.each(productInfo.photos, function (photo) {
                                myAdPicItems.push({
                                    xtype: 'panel',
                                    items: {html: "<img src='" + photo.url + "' style='width:100%;height:100%;'  / > "}
                                });
                            });
                        } else {
                            myAdPicItems.push({
                                xtype: 'panel',
                                items: {html: "<img src='" + productInfo.picurl + "' style='width:100%;height:100%;'  / > "}
                            });
                        }
                        var productCarousel = Ext.getCmp('productCarousel');
                        productCarousel.setItems(myAdPicItems);
                        productCarousel.setActiveItem(0);
                    }

                    Ext.getCmp('showProductGrade').setHtml("<img src='resources/images/product_grade_"+productInfo.grade+".png'  class='img97'>");
                    Ext.getCmp('showProductName').setHtml(productInfo.name);
                    Ext.getCmp('showProductExplain').setHtml(productInfo.explain);
                    Ext.getCmp('showProductView').setHtml(productInfo.viewnum);
                    Ext.getCmp('showProductMark').setHtml(productInfo.marketnum);
                    if (productInfo.isorder == 1) {
                        Ext.getCmp('showProductIsOrder').setHidden(false);
                    }
                    var myProductStandard = [];
                    if (!Ext.isEmpty(productInfo.standards)) {
                        var prostand = productInfo.standards;
                        for (i = 0; i < prostand.length; i++) {
                               var standPrice;
                            if (productInfo.isviewbate == 1) {
                                standPrice = prostand[i].reprice;
                                Ext.getCmp('viewProductPrice').setHidden(false);
                            } else {
                                standPrice = prostand[i].price;
                                Ext.getCmp('viewProductPrice').setHidden(true);
                            }
                            if (i == 0) {
                                myProductStandard.push(
                                    { xtype: 'radiofield',
                                        name: 'standard',
                                        cls: 'x-container2',
                                        label: prostand[i].name + '：' + prostand[i].explain + ' (<span style="color:#730017">￥' + standPrice + '</span>)',
                                        checked: true,
                                        labelWidth: '90%',
                                        value: prostand[i].cpsid
                                    });
                                Ext.getCmp('showProductPrice').setHtml('<S>￥'+prostand[i].price+' </S>');
                                Ext.getCmp('countPrice').setValue('￥' + (standPrice * Ext.getCmp('numbers').getValue()));
                            } else {
                                myProductStandard.push(
                                    { xtype: 'radiofield',
                                      name: 'standard',
                                      label: prostand[i].name + '：' + prostand[i].explain+' (<span style="color:#730017">￥'+standPrice+'</span>)',
                                      labelWidth: '90%',
                                      cls:'x-container2',
                                      value: prostand[i].cpsid
                                    });
                            }
                        }
                    }
                    Ext.getCmp('productStandard').setItems(myProductStandard);
                    Ext.getCmp('toolbar').setTitle(productInfo.name)
                    var productAssess = Ext.getStore('ProductAssess');
                    productAssess.load({
                        params: {cpid: cpid},
                        callback: function(data) {
                            if(data.length>0){
                            Ext.getCmp('praiseList').setHeight('' + data.length * 110 + 'px');
                            }
                        }});
                    if (window.localStorage.getItem('app_Login_id') != null) {
                        Ext.Ajax.request({
                            url: Global.api_url + '/cloud/1/collect_for_user',
                            params: {cpid: cpid,cuid:window.localStorage.getItem('app_Login_id')},
                            scope: this,
                            success: function (response) {
                                var result = Ext.decode(response.responseText);
                                if (result.Variables.Result.code == 0 && result.Variables.data==1 ) {
                                    Ext.getCmp('productCollect').addCls('heart');
                                }
                            }})
                    }
                    Ext.Viewport.animateActiveItem(product, {type: 'slide', direction: 'left'});
                    Ext.Viewport.unmask();
                } else {
                    Ext.Viewport.unmask();
                    cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", [result.Variables.Message.messagestr]);
//                    Ext.Msg.alert(result.Variables.Message.messagestr);
                }
            },
            failure: function () {
                Ext.Viewport.unmask();
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", ['请求失败,服务器维护中...']);
//                Ext.Msg.alert('请求失败', '服务器维护中....');
            }
        });
    },
    addCars: function () {
        Ext.Viewport.mask({
            xtype: 'loadmask',
            message: '正在加入...'
        });
        if (window.localStorage.getItem('app_Login_id') == null) {
            Ext.Viewport.unmask();
            Ext.Viewport.animateActiveItem('loginForm', {type: 'slide', direction: 'left'});
            return false;
        }
        Ext.Ajax.request({
            url: Global.api_url + '/cloud/1/shopping_cart_add',
            method: 'POST',
            params: {
                cadid: window.localStorage.getItem('app_district_id'),
                cuid: window.localStorage.getItem('app_Login_id'),
                cpid: productInfo.cpid,
                cpsid: this.getRadioFields().getGroupValue(),
                pnumber: Ext.getCmp('numbers').getValue()
            },
            scope: this,
            success: function (response) {
                Ext.Viewport.unmask();
                var result = Ext.decode(response.responseText);
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", [result.Variables.Message.messagestr]);
//                Ext.Msg.alert(result.Variables.Message.messagestr);
                if (result.Variables.Result.code == 0) {

                }
            },
            failure: function () {
                Ext.Viewport.unmask();
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", ['请求失败,服务器维护中...']);
//                Ext.Msg.alert('请求失败', '服务器维护中....');
            }
        });
    },
    sellProduct: function () {
        Ext.Viewport.mask({
            xtype: 'loadmask',
            message: '正在提交数据...'
        });

        if (window.localStorage.getItem('app_Login_id') == null) {
            Ext.Viewport.unmask();
            Ext.Viewport.animateActiveItem('loginForm', {type: 'slide', direction: 'left'});
            return false;
        }
        Ext.Ajax.request({
            url: Global.api_url + '/cloud/1/shopping_cart_add',
            method: 'POST',
            params: {
                cadid: window.localStorage.getItem('app_district_id'),
                cuid: window.localStorage.getItem('app_Login_id'),
                cpid: productInfo.cpid,
                cpsid: this.getRadioFields().getGroupValue(),
                pnumber: Ext.getCmp('numbers').getValue()
            },
            scope: this,
            success: function (response) {
                Ext.Viewport.unmask();
                var result = Ext.decode(response.responseText);
                // Ext.Msg.alert(result.Variables.Message.messagestr);
                if (result.Variables.Result.code == 0) {
                    var shoppingBalanceView = this.getShoppingBalanceView();
                    if (shoppingBalanceView == null) {
                        shoppingBalanceView = Ext.create('vacake.view.ShoppingBalance');
                    }
                    Ext.Viewport.animateActiveItem(shoppingBalanceView, {type: 'slide', direction: 'left'});
                } else {
                    cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", [result.Variables.Message.messagestr]);
                }
            },
            failure: function () {
                Ext.Viewport.unmask();
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", ['请求失败,服务器维护中...']);
//                Ext.Msg.alert('请求失败', '服务器维护中....');
            }
        });
    },
    collectProduct: function () {
        Ext.Viewport.mask({
            xtype: 'loadmask',
            message: '正在收藏中...'
        });
        if (window.localStorage.getItem('app_Login_id') == null) {
            Ext.Viewport.unmask();
            Ext.Viewport.animateActiveItem('loginForm', {type: 'slide', direction: 'left'});
            return false;
        }
        Ext.Ajax.request({
            url: Global.api_url + '/cloud/1/collect_add',
            method: 'POST',
            params: {
                cuid: window.localStorage.getItem('app_Login_id'),
                cpid: productInfo.cpid,
                cadid: window.localStorage.getItem('app_district_id')
            },
            scope: this,
            success: function (response) {
                Ext.Viewport.unmask();
                var result = Ext.decode(response.responseText);
                Ext.getCmp('productCollect').addCls('heart');
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", [result.Variables.Message.messagestr]);
             },
            failure: function () {
                Ext.Viewport.unmask();
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", ['请求失败,服务器维护中...']);
             }
        });
    }

});

